package com.qms.app.utils;


import com.qms.app.bean.Permissions;
import com.qms.app.bean.Roles;
import com.qms.app.bean.Users;
import com.qms.app.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//登录认证类  在该类中 可以调用数据库进行认证用户信息的查询
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UsersService usersService;

   //处理用户登录用的
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String  username = (String) token.getPrincipal(); // 获得用户名称
        SimpleAuthenticationInfo info=null;
        Users user = login(username);
        if(user != null){
            // 链式编程
            SecurityUtils.getSubject().getSession().setAttribute("user",user);
            info = new SimpleAuthenticationInfo(user.getUname(),user.getPassword(),super.getName());
        }
        return info;
    }


    private Users login(String username){
        return usersService.login(username);
    }

    //处理用户角色权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String uname = (String )principals.getPrimaryPrincipal();// 获得已经登录的用户名称
        Users users = login(uname);
        List<Roles> list = users.getList(); // 根据这个用户名字 进行登录  通过当前的方法获取到对应用户有的角色信息
//        SimpleAuthorizationInfo  对象会在前端结合Shiro框架提供的jsp标签进行过滤
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  // 封装简单的授权信息
        List<String> rolerNames = new ArrayList<>();
        for (Roles roles:list) {
            rolerNames.add(roles.getRname());// 循环集合获得角色名称
            // 该方法需要添加一个集合  集合类型是String  不能直接将list进行加入 因为类型不匹配
            info.addRoles(rolerNames);
        }
        //所有的权限的名称
        List<String> perNames=new ArrayList<>();
        //该集合装载的是用于所有的权限
        List<Permissions> permissionsList = users.getPList();
        for (Permissions permissions : permissionsList) {
            perNames.add(permissions.getPname());
        }
        //将权限名称交给SimpleAuthorizationInfo对象
        info.addStringPermissions(perNames);
        return info;
    }

}
